package com.lyy.common.shiro;

import com.lyy.common.utils.SpringUtil;
import com.lyy.system.pojo.SysUser;
import com.lyy.system.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;


public class PswdRealm extends AuthorizingRealm {

    /**
     * 必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof PswdToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        PswdToken pswdToken = (PswdToken) authenticationToken;
        String username = pswdToken.getUsername();
        SysUserService userService = SpringUtil.getBean(SysUserService.class);
        SysUser user = userService.getUserByUserName(username);
        if (user == null) {
            throw new UnknownAccountException();
        }
        if (!user.getPassword().equals(userService.passwordEncoder(new String(pswdToken.getPassword()), user.getSalt()))) {
            throw new IncorrectCredentialsException();
        }
        if (!"0".equals(user.getUserFlag())) {
            throw new LockedAccountException();
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

}